package com.smmisia.article.core;


import com.smmisia.article.entity.Score;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

class UserCF {

    public static List<Integer> recommend(Integer userId, List<Score> list) {
        //按用户分组
        Map<Integer, List<Score>> userMap = list.stream().collect(Collectors.groupingBy(Score::getUserId));
        //获取其他用户与当前用户的关系值
        Map<Integer, Double> userDisMap = CoreMath.computeNeighbor(userId, userMap, 0);
        //获取关系最近的用户
        double maxValue = Collections.max(userDisMap.values());
        Set<Integer> userIds = userDisMap.entrySet()
                .stream().filter(e -> e.getValue() == maxValue).
                map(Map.Entry::getKey)
                .collect(Collectors.toSet());
        //取关系最近的用户
        Integer nearestUserId = userIds.stream().findAny().orElse(null);
        if (nearestUserId == null) {
            return Collections.emptyList();
        }
        //最近邻用户看过文章列表
        List<Integer> neighborItems = userMap.get(nearestUserId)
                .stream()
                .map(Score::getArticleId)
                .collect(Collectors.toList());
        //指定用户看过文章列表
        List<Integer> userItems = userMap.get(userId)
                .stream()
                .map(Score::getArticleId)
                .collect(Collectors.toList());
        //找到最近邻看过，但是该用户没看过的文章列表
        neighborItems.removeAll(userItems);
        return neighborItems;
    }
}
